package com.guigu.servicegoods.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.TbOrderItem;
import com.guigu.servicegoods.domain.TbSku;
import com.guigu.servicegoods.service.SkuSearchService;
import com.guigu.servicegoods.service.TbSkuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@RestController
@RequestMapping("/servicegoods/tbsku")
public class TbSkuController {

    @Autowired
    private TbSkuService skuService;

    @Autowired
    private SkuSearchService skuSearchService;

    /**
     * 全文检索
     * @param searchMap
     * @return
     */
    @GetMapping("search")
    public Map search(@RequestParam Map<String,String> searchMap){
        return skuSearchService.search(searchMap);
    }

    /**
     * 该请求处理将所有数据插入到my_sku12索引库中
     * @return
     */
    @GetMapping("/findAllES")
    public Result findAllES(){
        List<TbSku> skuList = skuService.list(null);

        // 1.连接Rest接口
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder restClientBuilder = RestClient.builder(http).setMaxRetryTimeoutMillis(1000*60*10); //rest构建器
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder); //高级客户端对象（连接）

        //2. 封装请求的对象
        BulkRequest bulkRequest = new BulkRequest();
        for(TbSku sku: skuList){
            IndexRequest indexRequest = new IndexRequest("my_sku12", "doc", sku.getId());
            Map skuMap = new HashMap<>();
            skuMap.put("name",sku.getName());
            skuMap.put("brandName",sku.getBrandName());
            skuMap.put("categoryName",sku.getCategoryName());
            skuMap.put("price",sku.getPrice());
            skuMap.put("image", sku.getImage());
            skuMap.put("spuId", sku.getSpuId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date createTime = sku.getCreateTime();
            if(createTime!=null)
                skuMap.put("createTime", sdf.format(sku.getCreateTime()));
            else
                skuMap.put("createTime", null);
            skuMap.put("saleNum", sku.getSaleNum());
            skuMap.put("commentNum", sku.getCommentNum());

            Map<String, String> spec = JSON.parseObject(sku.getSpec(), Map.class);
            skuMap.put("spec",spec);
            indexRequest.source(skuMap);

            bulkRequest.add(indexRequest);
        }

        //3. 获取请求结果
        try {
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            int status = bulkResponse.status().getStatus();
            System.out.println(status);
            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result().data("skuList",skuList);
    }



    @GetMapping("/findByIdPrice")
    public Result findByIdPrice(String skuId) {
        Integer price = skuService.findByIdPrice(skuId);
        System.out.println(price);
        return Result.ok().data("price",price);
    }

    @GetMapping("/findBySpuId")
    public Result findBySpuId(String spuId){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("spu_id",spuId);
        List<TbSku> skuList = skuService.list(wrapper);
        return Result.ok().data("sku",skuList);
    }

    @PostMapping("fingPage")
    public Result findPage(@RequestBody(required = false) Map<String,Object> searchMap, Integer page, Integer size){
        return skuService.findPage(searchMap,page,size);
    }

    @PostMapping("insert")
    public Result insert(@RequestBody TbSku sku){
        if(skuService.save(sku)){
            return Result.ok();
        }
        return Result.error();
    }

    @PostMapping("update")
    public Result update(@RequestBody TbSku sku){
        if (skuService.updateById(sku)){
            return Result.ok();
        }
        return Result.error();
    }

    @GetMapping("delete")
    public Result delete(String id){
        if (skuService.removeById(id)){
            return Result.ok();
        }
        return Result.error();
    }

    @GetMapping("findById")
    public Result findById(String id){
        TbSku sku = skuService.getById(id);
        if (sku == null){
            return Result.error();
        }
        return Result.ok().data("sku",sku);
    }

    @GetMapping("findById2")
    public TbSku findById2(String id){
        return skuService.getById(id);
    }

    @PostMapping("deductionStock")
    public boolean deductionStock(@RequestBody List<TbOrderItem> oderItemList) {
        return skuService.deductionStock(oderItemList);
    }



    //谢尚峰插入
    @PostMapping("findList")
    public Result findList(@RequestBody Map<String, Object> searchMap){
        List<TbSku> list = this.skuService.findList(searchMap);
        if(list!=null)
            return Result.ok().data("list",list);
        return Result.error();
    }

    // 查询所有数据
    @GetMapping("findAll")
    public Result findAll(){
        List<TbSku> skus = this.skuService.findAll();
        if(skus!=null)
            return Result.ok().data("skus",skus);
        return Result.error();
    }
}

